﻿/* MIT License:
 *
 *
 * Copyright 2010 Anonyme s.r.o. (http://www.anonyme.cz)
 *
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinqToHTML;
using System.Text.RegularExpressions;

namespace AnonymeCz.VodafonePark
{
    public class VodafoneParkProvider
    {
        private string _userName;
        private string _password;

        public VodafoneParkProvider(string userName, string password)
        {
            this._userName = userName;
            this._password = password;
        }

        public void SendMessage(string recipient, string text)
        {
            using (var _client = new CookieAwareWebClient())
            {
                _client.Encoding = UTF8Encoding.UTF8;
                var loginResponse = _client.DownloadString(String.Format("https://park.vodafone.cz/login?email={0}&password={1}", System.Web.HttpUtility.UrlEncode(_userName), System.Web.HttpUtility.UrlEncode(_password)));
                var token = _getToken(loginResponse);

                if (String.IsNullOrEmpty(token))
                    throw new Exception("Login failed!");


                // Send message
                var response = _client.DownloadString(String.Format("https://park.vodafone.cz/gateway?x={0}&recipients%3ArecipientInput={1}&text={2}&gatewayPanel%3Agateway%3AmessagePanel%3AsendButton=1",
                    token,
                    System.Web.HttpUtility.UrlEncode(recipient),
                    System.Web.HttpUtility.UrlEncode(text)
                    ));

                if (!Regex.IsMatch(response, "Zpráva byla úspešně odeslána", RegexOptions.IgnoreCase))
                    throw new Exception("Message sending error - maybe wrong number.");
            }
        }

        /// <summary>
        /// Returns Token key for "buttonSendMessage" action
        /// </summary>
        /// <param name="data">Html page with SMS form</param>
        /// <returns>Token</returns>
        private string _getToken(string data)
        {
            var token = String.Empty;
            var elements = LinqToHtml.FromString(data);

            // Get the onclick="" attribute from the <a name="gatewayPanel:gateway:messagePanel:sendButton" /> element
            var onclickAttribute = (from e in elements
                                    where
                                        e.Name == "a"
                                        &&
                                        (e.Attribute("name") != null && e.Attribute("name").Value == "gatewayPanel:gateway:messagePanel:sendButton")
                                        &&
                                        e.Attribute("onclick") != null
                                    select Regex.Replace(e.Attribute("onclick").Value, @"\s+", String.Empty)).FirstOrDefault();

            if (onclickAttribute != null)
            {
                token = Regex.Match(onclickAttribute, @"wicketSubmitFormById\('id[a-zA-Z0-9]+','\?x\=([^,]+)'").Groups[1].Value;
            }
            
            return token;
        }
    }
}
